﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AspMvcWebClient.GameServiceReference;
using AspMvcWebClient.PlayerServiceReference;
using AspMvcWebClient.ExampleDataCalls;
using AspMvcWebClient.Models;

namespace AspMvcWebClient.Controllers
{
    public class HomeController : Controller
    {

        private GameServiceClient gameService;

        public HomeController()
        {
            gameService = new GameServiceClient();
        }

        public ActionResult Index()
        {
            ViewBag.test = "Hejsan";

            return View("Login");
        }

        public ActionResult CheckLogin(string user, string pass)
        {
            var playerService = new PlayerServiceClient();
            var userObj = playerService.LoginPlayer(user, pass);

            if (userObj != null) // Jämför inmatade namnet med databasen
            {
                Session["User"] = userObj.Name;
                Session["UserId"] = userObj.ID;
                ViewBag.user = userObj.Name;
                return GoToStart();

            }
            else
            {
                ViewBag.FailMessage = "Inloggningen misslyckades.";
                return View("Login");
            }

        }

        public ActionResult CreateGame(string gameSelect, string roundsSelect)
        {
            //Nollställer felmeddelande
            ViewBag.CreateLobbyError = "";

            int numOfRounds;
            Int32.TryParse(roundsSelect, out numOfRounds);

            int gameId;
            Int32.TryParse(gameSelect, out gameId);

            int userId;
            Int32.TryParse(Session["UserId"].ToString(), out userId);



            GameLobby gameLobby = gameService.CreateGame(userId, gameId, numOfRounds); //Om den failar?

            if (gameLobby != null)
            {
                return GoToStart();
            }
            else
            {
                ViewBag.CreateLobbyError = "Gick inte att starta lobbyn";
                return NewGame();
            }

        }

        /// <summary>
        /// Hämtar speltitlar och spelsessioner som spelaren kan joina. Visar sidan för att starta ett spel.
        /// </summary>
        /// <returns></returns>
        public ActionResult NewGame()
        {
            int userId;
            Int32.TryParse(Session["UserId"].ToString(), out userId);



            GetGameTitles();
            ViewBag.Games = gameService.GetListOfAllGameTypes();

            var model = gameService.GetListOfJoinableGames(1, userId);

            return View("NewGame", model);
        }

        public void GetActiveGames() //Hämta användarens spel ("spelsessioner")
        {
            int userId;
            Int32.TryParse(Session["UserId"].ToString(), out userId);


            ViewBag.Games = gameService.GetListOfPlayersActiveGamesByGameType_Init(userId, 1);
        }

        public void GetGameTitles() // Hämta alla speltitlar
        {

            ViewBag.GameTitles = gameService.GetListOfAllGameTypes();
        }

        public bool SubmitTurn(string choice, string gameId)
        {
            var sux = choice;

            int choiceInt;
            Int32.TryParse(choice, out choiceInt);

            int userId;
            Int32.TryParse(Session["UserId"].ToString(), out userId);

            int _gameId;
            Int32.TryParse(gameId, out _gameId);

            bool choiceSuccess = gameService.MakePlayerChoice(_gameId, userId, choiceInt);

            //1. Är spelet aktivt?
            //2. Finns en vinnare?
            //3. Finns spelaren med i spelet?
            //4. Har spelaren redan gjort ett val i denna rond? 

            return choiceSuccess;
        }

        //public ActionResult CheckTurn()
        //{
        //    //Kalla på relevant serviceclient-metod som kontrollerar vems tur det är.
        //    //Data för användare samt spelsessions id finns sparat i sessionsvariablerna User samt GameSessionId

        //    AspMvcWebClient.GameServiceReference.Player p1 = new AspMvcWebClient.GameServiceReference.Player();
        //    p1.ID = 1;
        //    p1.Mail = "martin@rsp.nu";
        //    p1.Name = "AssSlayer666";

        //    AspMvcWebClient.GameServiceReference.Player p2 = new AspMvcWebClient.GameServiceReference.Player();
        //    p2.ID = 2;
        //    p2.Mail = "oskar@rsp.nu";
        //    p2.Name = "PounderThatCheeseQuad";

        //    AspMvcWebClient.GameServiceReference.game g = new AspMvcWebClient.GameServiceReference.GameInfo();
        //    g.TotalNumOfGameRounds = 3;
        //    g.WinningPlayerID = 1;

        //    AspMvcWebClient.GameServiceReference.PlayerChoice c1 = new AspMvcWebClient.GameServiceReference.PlayerChoice();
        //    c1.GameRoundID = 1;
        //    c1.ChoiceMade = 1;
        //    c1.DateOfChoice = DateTime.Now;
        //    c1.PlayerID = 1;

        //    AspMvcWebClient.GameServiceReference.PlayerChoice c2 = new AspMvcWebClient.GameServiceReference.PlayerChoice();
        //    c2.GameRoundID = 1;
        //    c2.ChoiceMade = 3;
        //    c2.DateOfChoice = DateTime.Now;
        //    c2.PlayerID = 2;

        //    GameRoundWithPlayerChoices p = new GameRoundWithPlayerChoices();
        //    p.GameRoundNumber = 1;
        //    p.WinningPlayer = p1;
        //    p.PlayerChoices = new List<AspMvcWebClient.GameServiceReference.PlayerChoice>();

        //    p.PlayerChoices.Add(c1);
        //    p.PlayerChoices.Add(c2);

        //    List<GameRoundWithPlayerChoices> l = new List<GameRoundWithPlayerChoices>();
        //    l.Add(p);

        //    g.PlayedGameRounds = l;

        //    return Json(g, JsonRequestBehavior.AllowGet);
        //}

        public ActionResult GoToStart()
        {
            GetActiveGames();
            //TODO: Hämta spel i lobby (ej påbörjade)
            //TODO: Hämta avslutade spel (x antal, avslutade inom x antal timmar)
            return View("Start");
            
        }

        public ActionResult ShowGame(string gameId)
        {
            var gameID = int.Parse(gameId);

            int userId;
            Int32.TryParse(Session["UserId"].ToString(), out userId);


            ActiveGameInfo_Init game = gameService.GetActiveGameInfo_Init(gameID, userId);
            Session["ActiveGameInfo"] = game;

            if (game != null)
            {
                return View("RockPaperScissor", game);
            }
            else
            {
                GoToStart();
                return View("Start");
            }
        }

        /// <summary>
        /// Tar emot ett id (som representerar vilken spelsession spelaren ska joina)
        /// Lägger till spelaren, genom spelarens, id till spelsessionen i fråga
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult JoinGame(string id)
        {
            int userId;
            Int32.TryParse(Session["UserId"].ToString(), out userId);

            int gameId;
            Int32.TryParse(id, out gameId);

            bool joinSuccess = gameService.JoinGame(gameId, userId);

            if (joinSuccess)
            {
                return GoToStart();
            }
            else                    {
                //Kör upp ngt i röven
                return null;
            }

        }

        /// <summary>
        /// Frågar WCF:en om motståndarens status (om hen gjort ett val eller inte)
        /// </summary>
        /// <param name="playerId"></param>
        /// <param name="gameSessionId"></param>
        /// <returns></returns>
        public ActionResult CheckGameStatus(string gameId)
        {
            int _playerId;
            Int32.TryParse(Session["UserId"].ToString(), out _playerId);  

            int _gameId;
            Int32.TryParse(gameId, out _gameId);

            int _playerChoice = 0;
            int _opponentChoice = 0;

            ActiveGameInfo_Poll activeGameInfo_Poll_latest = gameService.GetActiveGameInfo_Poll(_gameId, _playerId);
            ActiveGameInfo_Poll activeGameInfo_Poll = (ActiveGameInfo_Poll)Session["ActiveGameInfo_Latest"];
            ActiveGameInfo_Init activeGameInfo_Init = (ActiveGameInfo_Init)Session["ActiveGameInfo"];

            if (activeGameInfo_Poll_latest.GameState == GameState.Playing) //Om spelet är över
            {
                    if (!activeGameInfo_Poll_latest.Equals(activeGameInfo_Poll))
                    {
                        if (activeGameInfo_Poll_latest.PlayedGameRounds.OrderBy(x => x.GameRoundNumber).Last() != null) //Finns det en vinnare? WinningPlayer i playedrounds lr vad den heter
                        {
                            //Finns en vinnare --> Visa resultat
                            foreach (var playedGameRound in activeGameInfo_Poll_latest.PlayedGameRounds)
                            {
                                foreach (var playerChoice in playedGameRound.PlayerChoices)
                                {
                                    if (playerChoice.Player.ID != _playerId)
                                    {
                                        _opponentChoice = playerChoice.ChoiceMade;
                                    } if (playerChoice.Player.ID == _playerId)
                                    {
                                        _playerChoice = playerChoice.ChoiceMade;
                                    }
                                }
                            }
                            //Rundan är över - returnera spelarnas val (spelaren, motståndaren) och vinnaren.
                            return Json(new List<int>() { _playerChoice, _opponentChoice, activeGameInfo_Init.WinningPlayer.ID }, JsonRequestBehavior.AllowGet);
                        }
                    }
            }
            else
            {
                //Spelet är över
                return Json(new List<int>(new int[998]), JsonRequestBehavior.AllowGet); //Skicka till ResultPage och visa slutresultat
            }

            Session["ActiveGameInfo_Latest"] = gameService.GetActiveGameInfo_Poll(_gameId, _playerId);
            return Json(new List<int>(new int[999]), JsonRequestBehavior.AllowGet);
        }

        public void GetActiveGameInfo_Init(string gameId)
        {
            int _playerId;
            Int32.TryParse(Session["UserId"].ToString(), out _playerId);

            int _gameId;
            Int32.TryParse(gameId, out _gameId);

            try
            {
                Session["ActiveGameInfo"] = gameService.GetActiveGameInfo_Init(_gameId, _playerId);
            }
            catch (Exception)
            {

                throw;
            }
        }

        public ActionResult showEndResult(ActiveGameInfo_Poll acpoll) {
            //ActiveGameInfo_Poll acpoll = gameService.GetActiveGameInfo_Poll(60, 8);

            return View("ResultPage",acpoll);
        }
    }
}
